package com.ipworkbench.common.db;

import java.sql.Connection;
import java.sql.SQLException;

import com.ipworkbench.common.util.IPWException;

/**
 * jdbc事务管理器
 * 
 * @author zhangfaheng
 *
 * @date May 15, 2010
 */
public class TransactionManager {
	
//	private Connection conn;
	
//	protected final Logger logger = Logger.getLogger(this.getClass());
	
	private static final ConnectionFactory connFactory;
    static {
        connFactory = ConnectionFactory.getInstace();
    }

    public static final ThreadLocal<Connection> local = new ThreadLocal<Connection>();
    /**
     * 开始事务
     * @throws IPWException 
     */
    public static void beginTransaction() throws IPWException {
        Connection conn = (Connection) local.get();
        try {
            if (null == conn  || conn.isClosed()) {
                conn = connFactory.takeConnection();
                local.set(conn);
            }
            conn.setAutoCommit(false);
        } catch (SQLException e) {
            throw new IPWException("开始事务出现异常",e);
        }
    }

    /**
     * 提交事务
     */
    public static void commitAndClose()  throws IPWException{
        Connection conn = (Connection) local.get();
        if (conn != null) {
            try {
                conn.commit();
               //conn.setAutoCommit(true);
            } catch (SQLException e) {
                throw new IPWException("提交事务出现异常",e);
            }finally{
            	endTransaction();
            }
        }
    }

    /**
     * 回滚事务
     */
    public static void rollbackAndClose() throws IPWException{
        Connection conn = (Connection) local.get();
        if (null !=  conn) {
            try {
                conn.rollback();
               // conn.setAutoCommit(true);
            } catch (SQLException e) {
                throw new IPWException("回滚事务出现异常",e);
            }finally{
            	endTransaction();
            }
        }
    }

    /**
     * 结束事务
     */
    public static void endTransaction() throws IPWException{
    	
        Connection conn = (Connection) local.get();        
        if (null !=  conn) {
            try {
            	//local.set(null);
                local.remove(); // 卸装线程绑定
                conn.close();
            } catch (SQLException ex) {
                throw new IPWException(ex.getMessage());
            }
            conn = null;
        }
    }


}
